package cn.dxj1016.lesson04;

import cn.dxj1016.lesson02.utils.JdbcUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class TestTransaction2 {
    public static void main(String[] args) {
        Connection connection = null;
        PreparedStatement preparedStatement = null;

        try {
            connection = JdbcUtils.getConnenction();
//            关闭自动提交事务
            connection.setAutoCommit(false);
            String sql1 = "UPDATE  account SET money=money-100 WHERE `NAME`='A';";
            preparedStatement = connection.prepareStatement(sql1);
            preparedStatement.executeUpdate();

            int x = 1 / 0;//报错，回滚

            String sql2 = "UPDATE  account SET money=money+100 WHERE `NAME`='B';";
            preparedStatement = connection.prepareStatement(sql2);
            preparedStatement.executeUpdate();
//            业务完毕，提交事务
            connection.commit();
            System.out.println("成功");

        } catch (Exception e) {
            try {
                connection.rollback();
                System.out.println("捕获到异常，回滚");
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
            e.printStackTrace();
        }finally {
            JdbcUtils.release(connection,preparedStatement,null);
        }

    }
}
/*
执行结果：
捕获到异常，回滚
java.lang.ArithmeticException: / by zero
	at cn.dxj1016.lesson04.TestTransaction2.main(TestTransaction2.java:22)
 */